package com.it.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.it.entity.OrderFrom;
import com.it.entity.Product;
import com.it.service.OrderService;
import com.it.service.ProductService;
import com.it.util.ItdragonUtils;
import com.it.util.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 〈数据统计实现接口〉<br>
 * @since 1.0.0
 */
@Controller
@RequestMapping("/statistics")
public class StatisticsController {
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ItdragonUtils itdragonUtils;

    /**
     * 管理界面跳转
     *
     * @param mv
     * @return
     */
    @RequestMapping("/sale.do")
    public ModelAndView sale(ModelAndView mv) {
        //查询出每个商品,在查询出每个商品的销量
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        List<Product> productList = productService.getProductList();
        for (Product product : productList) {
            nameList.add(product.getName());
            numberList.add(orderService.getOrderDetailsByProductId(product.getId()).size());
        }
        Page<OrderFrom> orderFromPage = orderService.selectPage(new OrderFrom(), 1, 1000);
        Map<String, List<OrderFrom>> resMap = ListUtils.groupBy(orderFromPage.getRecords(), new ListUtils.GroupBy<String, OrderFrom>() {
            @Override
            public String groupBy(OrderFrom row) {
                String ktrq = row.getTime();
                String ktrqStr = "";
                if (ktrq != null) {
                    ktrqStr = ktrq.substring(5, 7);
                }
                return ktrqStr;
            }
        });
        List<String> timeList = new ArrayList<>();
        List<Integer> orderNumberList = new ArrayList<>();
        for (Map.Entry<String, List<OrderFrom>> m : resMap.entrySet()) {
            System.out.println("key:" + m.getKey() + " value:" + m.getValue());
            timeList.add("2023-" + m.getKey());
            orderNumberList.add(m.getValue().size());
        }
        mv.addObject("nameList", nameList);
        mv.addObject("numberList", numberList);
        mv.addObject("timeList", timeList);
        mv.addObject("orderNumberList", orderNumberList);
        mv.setViewName("/statistics/sale");
        return mv;
    }

}